<template>
  <van-nav-bar
    title="地址列表"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />
  <van-address-list
    v-model="chosenAddressId"
    :list="addressList"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    @select="onSelect"
  />
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { showToast } from "vant";
import { addressApi } from "@/api/index";
import { useRoute, useRouter } from "vue-router";
import { appStore } from "@/store/appStore";
import { storeToRefs } from "pinia";
let { userId, phone } = storeToRefs(appStore());

const route = useRoute(); //不带r的是获取当前页面url相关参数
const router = useRouter(); //代r的是负责页面跳转
const chosenAddressId = ref(0);
const addressList = ref([]);
onMounted(() => {
  callAddressApi();
});
const callAddressApi = () => {
  addressApi.getList.call({ userId: userId.value }).then((res: any) => {
    res.forEach((item: any) => {
      item.address =
        item.province + item.city + item.country + item.addressDetail;
      item.tel = item.phone;
      if (item.isDefault === 0) {
        item.isDefault = true;
      } else {
        item.isDefault = false;
      }
    });

    addressList.value = res;
    const defaultAddress = res.filter(
      (item: any) => item.isDefault === true
    )[0];
    if (defaultAddress != undefined) {
      chosenAddressId.value = defaultAddress.id;
    }
  });
};

const onSelect = (item: any, index: number) => {
  addressApi.updateDefault
    .call({ id: item.id, userId: userId.value })
    .then((res: any) => {
      const defaultAddress: any = addressList.value.filter((item: any) => item.isDefault === true)[0];
            if(defaultAddress != undefined){
              defaultAddress.isDefault = false
             }
            item.isDefault = true
    });
};
const onAdd = () => {
  router.push({ name: "address-add" });
};
const onEdit = (item: any, index: any) => {
  router.push({ name: "address-edit", query: { id: item.id } });
};

const onClickLeft = () => history.back();
</script>
<style scoped>
</style>